package com.msh.starter.ip.analysis.utils;

import com.msh.frame.client.exception.BizException;
import com.msh.frame.client.exception.ServerException;
import com.msh.starter.ip.analysis.model.IpLocation;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;

@Slf4j
public class Ip2regionUtils {
    private static final Searcher searcher;
    /**
     * 字符常量0
     */
    private static final String ZERO="0";
    static {
        try (InputStream inputStream = Ip2regionUtils.class.getResourceAsStream("/ip2region.xdb");) {
            byte[] bytes = inputStream.readAllBytes();
            searcher = Searcher.newWithBuffer(bytes);
        } catch (IOException e) {
            throw new ServerException("ip解析器加载失败");
        }
    }



    /**
     * 根据iP获取归属地信息
     * @return
     */
    public static IpLocation getLocation(String ip) {
        try {
            String region = searcher.search(ip);
            if (StringUtils.hasText(region)) {
                IpLocation location = new IpLocation();
                // xdb返回格式 国家|区域|省份|城市|ISP，
                // 只有中国的数据绝大部分精确到了城市，其他国家部分数据只能定位到国家，后前的选项全部是0
                String[] result = region.split("\\|");
                location.setCountry(ZERO.equals(result[0])?"":result[0]);
                location.setProvince(ZERO.equals(result[2])?"":result[2]);
                location.setCity(ZERO.equals(result[3])?"":result[3]);
                location.setIsp(ZERO.equals(result[4])?"":result[4]);
                return location;
            }
        } catch (Exception e) {
            log.warn("解析地址失败: {}", ip);
            throw new BizException("解析地址[" + ip + "]失败");
        }
        return null;
    }
}
